import axios from 'axios'
import router from '@/router'
import LoadingManager from './loading-manager'
import { handleError } from './error-handler'
import { getToken, removeCookie } from '@/utils/utils'
import store from '../store'
let mac = localStorage.getItem('mac')
const http = axios.create({
  baseURL: process.env.VUE_APP_API_ROOT,
  headers: { post: { 'Content-Type': 'application/json' }, mac: mac ? mac : '' },
  isLoading: true, // 是否加载全局 loading
  catchError: true, // 是否统一处理异常
})

// 请求拦截器
http.interceptors.request.use(
  config => {
    // 默认加载全局 loading，若不需要加载则手动设置 isLoading 为 false
    // 例如：http.get(url, { isLoading: false })
    config.isLoading && LoadingManager.showFullSrceenLoading()
    //config.baseURL = 'http://111.1.139.66:8081';

    if (config.url.indexOf('login') === -1) {
      config.headers['Authorization'] = getToken()
    }

    return config
  },
  error => {
    // 关闭全局 loading
    error.response.config.isLoading && LoadingManager.hideFullScreenLoading()
    return handleError(error.response)
  }
)

// 响应拦截器
http.interceptors.response.use(
  response => {
    // 关闭全局 loading
    response.config.isLoading && LoadingManager.hideFullScreenLoading()

    if (response.data.code === 200 || response.data.code === '200') {
      // 请求成功
      return response.data.data
    }
    if (response.headers['content-type'] === 'multipart/form-data;charset=utf-8') {
      return response
    }
    // 请求失败
    return handleError(response)
  },
  error => {
    // 关闭全局 loading
    try {
      error.response.config.isLoading && LoadingManager.hideFullScreenLoading()
    } catch (error) {
      LoadingManager.hideFullScreenLoading()
    }
    // 对响应错误做点什么
    let status = error.response.status
    if (status === 401) {
      // 跳转登录页
      setTimeout(() => {
        router.push({ name: 'Login' })
        removeCookie('Authorization')
        store.commit('setRouterList', [])
        store.commit('setAccessCode', [])
      }, 1000)
    }
    return handleError(error.response)
  }
)

export default http
